package me.zd.tool.hardlink.service;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class I18nService {
    public static final I18nService INS = new I18nService();

    public final String[] ALL_LANGUAGE_ARY;
    private final Map<String, Map<String, String>> multiLanguageMap = new HashMap<>();
    private Map<String, String> currentLanguageMap;

    private I18nService() {
        final String i18nFilePackage = "me/zd/tool/hardlink/i18n/";
        Properties _i18n = PropertiesService.loadFromResource(i18nFilePackage + "_i18n.properties");
        if (_i18n == null || !_i18n.containsKey("language.list")) {
            ALL_LANGUAGE_ARY = new String[0];
            currentLanguageMap = new HashMap<>();
            return;
        }
        String i18nList = _i18n.getProperty("language.list");
        ALL_LANGUAGE_ARY = i18nList.split("\\|");
        if (ALL_LANGUAGE_ARY.length == 0) {
            currentLanguageMap = new HashMap<>();
            return;
        }
        for (int i = 0; i < ALL_LANGUAGE_ARY.length; i++) {
            String lang = ALL_LANGUAGE_ARY[i];
            Properties p = PropertiesService.loadFromResource(i18nFilePackage + lang + ".properties");
            multiLanguageMap.put(lang, PropertiesService.toMap(p));
        }

        changeLanguage(null);
    }

    public boolean changeLanguage(String language) {
        if (language == null) {
            language = ALL_LANGUAGE_ARY[0];
        }
        Map<String, String> lMap = multiLanguageMap.get(language);
        if (lMap == null) {
            return false;
        }
        currentLanguageMap = new HashMap<>(lMap);
        return true;
    }

    public String get(String key) {
        return currentLanguageMap.getOrDefault(key, key);
    }

    public String format(String key, Object... objs) {
        String str = currentLanguageMap.get(key);
        if (str != null) {
            return MessageFormat.format(str, objs);
        } else {
            return key;
        }
    }

    public String getSpecifyLanguage(String language, String key) {
        Map<String, String> map = multiLanguageMap.get(language);
        if (map != null) {
            return map.getOrDefault(key, key);
        }
        return key;
    }
}
